package org.higginsexamples.mailboxserver;

import java.util.Hashtable;

import javax.servlet.ServletException;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.osgi.util.tracker.ServiceTracker;

public class Activator implements BundleActivator
{
	static Bundle BUNDLE;
	private HttpServiceTracker tracker;
	
	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start( BundleContext context ) throws Exception
	{
		BUNDLE = context.getBundle() ; // TODO dirty hack, because I don't know how to do it right

		System.out.println("Mailbox server started." );

		// start a tracker for HttpService, will register all
		HttpServiceTracker tracker = new HttpServiceTracker (context);
		tracker.open();
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop( BundleContext context ) throws Exception
	{
			// close the tracker again, will unregister all
			tracker.close();
			System.out.println("Mailbox server stopped." );
	}
	
	// HttpService Tracker
	
	/**
	 * This HttpServicTracker will handle lifecycle of HttpService and register
	 * / unregister all resources and servlets.
	 */
	private class HttpServiceTracker extends ServiceTracker {
		
		private BundleContext bundleContext;

		public HttpServiceTracker(BundleContext context) {
			super(context, "org.osgi.service.http.HttpService", null);
			bundleContext = context;
		}
		
		@Override
		public Object addingService(ServiceReference reference) {
			HttpService httpService = (HttpService) bundleContext.getService(reference);
			
			// register all at HttpService
			HttpContext httpContext ;
			httpContext = new BasicSecurityHttpContext();
			try {
				httpService.registerResources( "/index.html", "/html/index.html", httpContext);
				httpService.registerServlet( "/mailboxes", new MailboxRetrievalServlet(), new Hashtable(), httpContext );
			} catch (NamespaceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return httpService;
		}

		@Override
		public void removedService(ServiceReference reference, Object service) {
			HttpService httpService = (HttpService) service;
			// unregister all resources and servlet
			httpService.unregister("/mailboxes");
			httpService.unregister("/index.html");
			// unget service is done via tracker
			super.removedService(reference, service);
		}
		
	}

}
